#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2022/3/1 9:11
# @Author  : afraidbenq
# @File    : login.py
# @Software: PyCharm
# @Github  : github/afraidbenq
# @Email   : 329189987@qq.com
# @Desc    :
import time
import base64
import hashlib

import requests
import traceback
from common import logger


# 登录接口实例化会话对象例子
# def login():
#     s = requests.session()  # 实例化会话对象
#     loginUrl = "https://q.XXX.dos.lixinchuxing.cn/XXXX/wxlogin"
#     data = {"username": "********", "password": "******"}
#     header = {"Content-Type": "application/json; charset=UTF-8"}
#     try:
#         res = s.post(url=loginUrl, json=data, headers=header, verify=False)
#         print(res.cookies)
#         # 后续接口请求在header中要增加"X-CSRF-Token"属性，值为登录请求获取到的csrf-token值
#         token = res.cookies["csrf-token"]
#         s.headers.update = ({"X-CSRF-Token": token})
#         # 返回登录处理后的session对象
#         return s
#     except Exception as e:
#         print("登录异常".format(e))


# 工行API登录接口
def icbc_api_interface_login():
    s = requests.session()  # 实例化会话对象
    url = "http://47.112.108.0:9200"
    path = "/sys/internalLogin"
    data = {
        "phone": "18573440825",
        "code": "123456",
    }
    headers = {"Content-Type": "application/json; charset=UTF-8"}
    try:
        # 测试服必须触发发送验证码才能使用123456
        r = s.post(url=url + "/sys/getCaptcha", json=data, headers=headers, verify=False)
        r = s.post(url=url + path, json=data, headers=headers, verify=False)
        print(r.status_code)
        print(r.json())
        if r.status_code == 200:
            logger.info(f"{r.status_code} 登录成功\n")
            token = r.json()["data"]["tokenValue"]
            s.headers.update({"token": token})  # 拿到token更新会话头信息
            return s
        else:
            logger.error(f"{r.status_code} {r.json()['msg']}\n")

    except Exception as e:
        logger.error(f"登录异常 {e}\n")
        logger.error(f"{traceback.format_exc()}\n")


# 商城后台登录接口
# def login():
#     s = requests.session()
#     url = "http://192.168.100.14:28019"
#     path = "/manage-api/v1/adminUser/login"
#     data = {
#         "userName": "admin",
#         "passwordMd5": "e10adc3949ba59abbe56e057f20f883e"
#     }
#     headers = {"Content-Type": "application/json; charset=UTF-8"}
#     try:
#         r = s.post(url=url + path, json=data, headers=headers, verify=False)
#         # print(r.status_code)
#         # print(r.json())
#         if r.status_code == 200:
#             logger.info(f"{r.status_code} 登录成功\n")
#             token = r.json()["data"]["token"]
#             # print(token)
#             s.headers.update({"token": token})  # 拿到token更新会话头信息
#             return s
#         else:
#             logger.error(f"{r.status_code} {r.json()['msg']}\n")
#     except Exception as e:
#         logger.error(f"登录异常 {e}\n")
#         logger.error(f"{traceback.format_exc()}\n")


# 商城H5登录接口
# def login():
#     s = requests.session()
#     url = "http://192.168.100.14:28019"
#     path = "/api/v1/login"
#     data = {
#         "loginName": "13688847757",
#         "password": "a123456"
#     }
#     headers = {"Content-Type": "application/json; charset=UTF-8"}
#     try:
#         r = s.post(url=url + path, json=data, headers=headers, verify=False)
#         print(r.status_code)
#         print(r.json())
#         if r.status_code == 200:
#             logger.info(f"{r.status_code} 登录成功\n")
#             token = r.json()["data"]
#             # print(token)
#             s.headers.update({"token": token})  # 拿到token更新会话头信息
#             return s
#         else:
#             logger.error(f"{r.status_code} {r.json()['msg']}\n")
#     except Exception as e:
#         logger.error(f"登录异常 {e}\n")
#         logger.error(f"{traceback.format_exc()}\n")

# 龙存管登录接口
def dragon_story_tube_api_interface_login():
    s = requests.session()  # 实例化会话对象
    url = "http://dragon-depository-agent.oiltour.cn"
    path = "/depository/auth/getAppToken"
    data = {"app_id": "987654321", "app_key": "987654321", "app_secret": "987654321abcde", "user_id": "SJGD10"}
    headers = {"Content-Type": "application/x-www-form-urlencoded"}
    try:
        r = s.get(url=url + path, params=data, headers=headers, verify=False)
        print(r.status_code)
        print(r.json())
        if r.status_code == 200:
            logger.info(f"{r.status_code} 登录成功\n")
            token = r.json()["data"]["access_token"]
            s.headers.update({"Authorization": 'Bearer ' + token})  # 拿到token更新会话头信息
            return s
        else:
            logger.error(f"{r.status_code} {r.json()['msg']}\n")

    except Exception as e:
        logger.error(f"登录异常 {e}\n")
        logger.error(f"{traceback.format_exc()}\n")


# 油途系统后台登录接口
def oil_road_system_api_login():
    s = requests.session()
    url = "http://test_co.oiltour.cn/api"
    path = "/admin/token/login"
    mobile = "18688407439"
    nonce = "1234"
    password = "123456"
    timestamp = str(int(time.time()))
    data = {
        'mobile': mobile,
        'password': password,
        'nonce': nonce,
        'timestamp': timestamp,
        'sign': hashlib.md5((mobile + nonce + password + timestamp).encode('utf-8')).hexdigest()
    }
    headers = {"Content-Type": "application/json; charset=UTF-8"}
    try:
        r = s.post(url=url + path, json=data, headers=headers, verify=False)
        print(r.status_code)
        print(r.json())
        if r.status_code == 200:
            logger.info(f"{r.status_code} 登录成功\n")
            access_token = r.json()['data']['access_token']
            key = mobile + ':' + access_token + ':' + str(r.json()['data']['admin']['id'])
            key_b = bytes(key, 'utf-8')
            authentication = "USERID " + base64.b64encode(key_b).decode()
            s.headers.update({"authentication": authentication})
            return s
        else:
            logger.error(f"{r.status_code} {r.json()['msg']}\n")

    except Exception as e:
        logger.error(f"登录异常 {e}\n")
        logger.error(f"{traceback.format_exc()}\n")


#油途小程序登录接口
def oil_road_system_api_login():
    s = requests.session()
    url = "http://test_api.oiltour.cn"
    path = "/api/login"
    appid = "13688847757"
    type = "3"
    nonce = "1234"
    appsercet = "a123456"
    timestamp = str(int(time.time()))
    data = {
        'appid': appid,
        'appsercet': appsercet,
        'nonce': nonce,
        'timestamp': timestamp,
        'type': type,
        'sign': hashlib.md5((appsercet + appid + nonce + timestamp).encode('utf-8')).hexdigest()
    }
    headers = {"Content-Type": "application/json; charset=UTF-8"}
    try:
        r = s.post(url=url + path, json=data, headers=headers, verify=False)
        print(r.status_code)
        print(r.json())
        if r.status_code == 200:
            logger.info(f"{r.status_code} 登录成功\n")
            access_token = r.json()['data']['access_token']
            key = appid + ':' + access_token + ':' + str(r.json()['data']['client']['uid'])
            key_b = bytes(key, 'utf-8')
            authentication = "USERID " + base64.b64encode(key_b).decode()
            print(authentication)
            s.headers.update({"authentication": authentication})
            return s
        else:
            logger.error(f"{r.status_code} {r.json()['msg']}\n")

    except Exception as e:
        logger.error(f"登录异常 {e}\n")
        logger.error(f"{traceback.format_exc()}\n")


if __name__ == '__main__':
    # dragon_story_tube_api_interface_login()
    # oil_road_system_api_login()
    str1="MTg2ODg0MDc0Mzk6UW1vbHZLQU1xMjMzY0NIOFN5TERWdGlhRWV6VXA2ZEY6MTA="
    a=base64.b64decode(str1.encode())
    print(a)

